﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;


namespace GuidFinder_Plugin
{
    public class GuidFinder_Plugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =(ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName != "new_guidfinder")
                    return;

                string new_guidtofind = (string)entity["new_guidtofind"];
                OptionSetValue new_entitiestoquery=(OptionSetValue)entity["new_entitiestoquery"];
                string new_filterentities = "";
                if (entity.Contains("new_filterentities")){
                    new_filterentities =(string)entity["new_filterentities"];
                }

                if (new_entitiestoquery.Value == 100000000)//All. i need to retrieve all entities...
                {
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                          EntityFilters = EntityFilters.Entity,
                          RetrieveAsIfPublished = true
                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);
                    new_filterentities = ""; StringBuilder strEnts=new StringBuilder();
                    foreach (EntityMetadata met in response.EntityMetadata)
                    {
                        if (strEnts.Length > 0) strEnts.Append(",");
                        strEnts.Append(met.SchemaName.ToLower());
                    }
                    new_filterentities = strEnts.ToString();
                }

                //Quey for each entity to try to find the Guid.
                StringBuilder strLog = new StringBuilder(); string new_foundentity = "";
                string[] arrnew_filterentities=new_filterentities.Split(",".ToCharArray());
                
                for (int i = 0; i < arrnew_filterentities.Length; i++)
                {
                    string entityfilter = arrnew_filterentities[i].ToString();
                    Entity oEntidad = null;
                    try
                    {
                        oEntidad = service.Retrieve(entityfilter, new Guid(new_guidtofind), new ColumnSet(allColumns: true));
                    }
                    catch (System.Exception ex)
                    {
 
                    }

                    if (strLog.Length > 0) strLog.Append(Environment.NewLine);
                    strLog.Append(i.ToString());strLog.Append(": ");
                    if (oEntidad != null)
                    {
                        strLog.Append(entityfilter); strLog.Append(" ---> FOUND!");
                        new_foundentity = entityfilter;
                        break;
                    }
                    else 
                    {
                        strLog.Append(entityfilter); strLog.Append(" ---> NONE");
                    }
                }

                //add attributes
                entity.Attributes.Add("new_foundentity", new_foundentity);
                entity.Attributes.Add("new_executionlog", strLog.ToString());

            }

        }
    }
}
